package com.tianpengtech.common.model.fair;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.tianpengtech.common.model.AbstractBaseModel;
import com.tianpengtech.common.model.fairext.FairExt;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.task.TaskWh;
import com.tianpengtech.common.util.DateUtils;
import com.tianpengtech.common.util.ToolDateTime;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 实体类名-网红表 fair_wh
 *
 * @since Fri May 26 13:29:02 HKT 2017
 */
public class Fair extends AbstractBaseModel<Fair> {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	public static final Fair dao = new Fair();
	public static final String FAIR_CACHE_NAME = "fair";
	public static final String FAIR_CACHE_ATTR_KEY = "fair_attr_";
	public static final String FAIR_CACHE_TOP_CREATETIME = "fair_top_createtime_";
	public static final String FAIR_CACHE_CITY = "fair_city_";
	public static final String FAIR_CACHE_REGION = "fair_region_";


	public static final String QQ = "1005501"; 
	public static final String WEIXIN = "1005502";
	public static final String SINA = "1005503"; 
	
	public static final String ID = "id"; //
	public static final String NICK_NAME = "nick_name"; // 昵称
	public static final String AGE = "age"; // 年龄
	public static final String GENDER = "gender"; // 性别
	public static final String HEIGHT = "height"; // 身高
	public static final String PROVINCE = "province"; // 省
	public static final String CITY = "city"; // 市
	public static final String PHOTO = "photo"; //照片
	public static final String FANS = "fans"; // 粉丝数量
	public static final String DELETETAG = "deletetag"; // 删除标识
	public static final String CREATE_TIME = "create_time"; // 创建时间
	public static final String STATUS = "status"; // 状态
	public static final String PLATFORM="platform"; //所属平台
	public static final String CHANNEL="channel"; //渠道
	public static final String MOIBILE="mobile"; //手机号码
	public static final String PASS_WORD="password"; //密码
	public static final String ID_CARD="id_card"; //身份证
	public static final String PERSONAL_PHOTO="personal_photo"; //个人形象照片
	public static final String REMIND_MSG="remind_msg"; //是否消息提醒
	public static final String TRAN_PWD="tran_pwd"; //交易密码
	public static final String MONEY="money"; //可用余额
	public static final String BIRTHDAY="birthday"; //生日
	public static final String BG_PHOTO="bg_photo"; //手机背景图片
	public static final String DESCRIPT="descript"; //描述信息
	public static final String FANS_FEATURE="fans_feature"; //描述信息
	public static final String PRICE="price"; //网红价格区间
	public static final String VERSION="version"; //乐观锁校验字段
	public static final String SMS_SET="sms_set"; //短信设置提醒设置
	public static final String AVALIABLE_FEE="avaliable_fee"; //网红可用余额

	
	public static final int STATUS_UNAPPROVER=-1;
	public static final int STATUS_APPROVING=1;
	public static final int STATUS_SUCCESS=2;
	public static final int STATUS_FAILURE=3;
	
	public static final int DELETE_STATUS_YES=1;
	public static final int DELETE_STATUS_NO=0;


	public static final int GENDER_WOMEN=0;
	public static final int GENDER_MEN=1;


	public static final int REMIND_MSG_ON=1; //消息提醒
	public static final int REMIND_MSG_OFF=0; //消息不提醒





	//网红属性对照表相关属性
	public static final String FAIR_ATTR_RLT_TABLENAME="fair_wh_attr_relation"; //对照表 表名
	public static final String FAIR_ATTR_TABLENAME="fair_wh_attr"; //属性表表 表名
	
	public String status(){
		String result="";
		if(getInt(STATUS)==STATUS_APPROVING){
			result="审核中";
		}else if(getInt(STATUS)==STATUS_SUCCESS){
			result="审核成功";
		}else if(getInt(STATUS)==STATUS_FAILURE){
			result="审核失败";
		}else if(getInt(STATUS)==STATUS_UNAPPROVER){
			result="帐号未认证";
		}else{
			result="未知状态";
		}
		return result;
	}

	/**
	 * 获取点击量
	 * @return
	 */
	public long getClick(){
		Fair fair=dao.findFirst("select sum("+TaskWh.CLICK_NUM+") as num from "+ TaskWh.dao.tableName()+" where "+TaskWh.WH_ID +"=?",new Object[]{get(ID)});
		BigDecimal num =new BigDecimal(0);
		if(fair.get("num")!=null){
			num=fair.getBigDecimal("num");
		}
		return num.longValue();
	}


	/**
	 * 获取转化量
	 * @return
	 */
	public long getCvs(){
		Fair fair=dao.findFirst("select sum("+TaskWh.CVS_NUM+") as num from "+ TaskWh.dao.tableName()+" where "+TaskWh.WH_ID +"=?",new Object[]{get(ID)});
		BigDecimal num =new BigDecimal(0);
		if(fair.get("num")!=null){
			num=fair.getBigDecimal("num");
		}
		return num.longValue();
	}

	/**
	 * 获取接单数量
	 * @return
	 */
	public long getOrders(){
		Fair fair=dao.findFirst("select count(*) as count from "+ TaskWh.dao.tableName()+" where "+TaskWh.WH_ID +"=?",new Object[]{get(ID)});
		long count=fair.getLong("count");
		return count;
	}

	/**
	 * 获取转化率
	 * @return
	 */
	public String getInto(){
		Fair fair=dao.findFirstByCache(FAIR_CACHE_NAME,"cvss_"+get(ID),"select sum("+TaskWh.CVS_NUM+") as num from "+ TaskWh.dao.tableName()+" where "+TaskWh.WH_ID +"=?",new Object[]{get(ID)});
		BigDecimal cvs=fair.getBigDecimal("num");
		long click=getClick();
		double d=0;
		if(fair.getBigDecimal("num")!=null&&click>0){
			d=cvs.doubleValue()/click;
		}
		DecimalFormat df=(DecimalFormat) DecimalFormat.getInstance();
		df.applyPattern("##.##%");
		return df.format(d);
	}

	/**
	 * 获取平均点击量
	 * @return
	 */
	public String getAvgClick(){
		long click=getClick();
		long order=getOrders();
		if (click==0 || order==0){
			return 0+"";
		}
		double d = click*1.0/order;
		DecimalFormat df=(DecimalFormat) DecimalFormat.getInstance();
		df.applyPattern("##.##");
		return df.format(d)+"";
	}

	/**
	 * 获取平均转化率
	 * @return
	 */
	public String getAvgInto(){
		Fair fair=dao.findFirst("select sum("+TaskWh.CVS_NUM+") as num from "+ TaskWh.dao.tableName()+" where "+TaskWh.WH_ID +"=?",new Object[]{get(ID)});
		BigDecimal cvs= new BigDecimal(0);
		long click=getCvs();
		double d=0;
		if(fair.getBigDecimal("num")!=null && click>0){
			d = click*1.0/getOrders();
		}
		DecimalFormat df=(DecimalFormat) DecimalFormat.getInstance();
		df.applyPattern("##.##");
		return df.format(d);
	}




	/**
	 * 获取属性名称
	 * @return
	 */
	public String getAttrString(){
		List<Record> recordList=Db.findByCache(FAIR_CACHE_NAME,FAIR_CACHE_ATTR_KEY+get(ID),"select * from "+FAIR_ATTR_TABLENAME+" at left join "+FAIR_ATTR_RLT_TABLENAME+" ar on at.id=ar.attr_id  where at.deletetag=0 and ar.wh_id=?",new Object[]{get(ID)});
		StringBuffer attrs= new StringBuffer();
		for (Record record: recordList) {
			attrs.append(record.getStr("name"));
			attrs.append("/");
		}
		if (attrs.length()>0){
			attrs.deleteCharAt(attrs.length()-1);
		}
		return attrs.toString();
	}

	/**
	 * 获取省市信息
	 * @return
	 */
	public String getCityString(){
		Record record  = Db.findFirstByCache(FAIR_CACHE_NAME,FAIR_CACHE_CITY+get(ID),"select t.REGION_NAME tname,p.REGION_NAME pname from region t LEFT JOIN region p on t.PARENT_ID=p.REGION_ID where t.REGION_ID=?",new Object[]{get(CITY)});
		if (record!=null){
			return record.get("pname")+" "+record.get("tname");
		}else{
			return "-";
		}
	}

	/**
	 * 获取荣耀信息
	 * @return
	 */
	public List<FairExt> getExt(Integer type,long wh_id){
		String sql="select * from "+FairExt.dao.tableName()+" where "+FairExt.TYPE+" =? and "+FairExt.WH_ID+"=? order by id desc";
		return FairExt.dao.find(sql,type,wh_id);
	}

	/**
	 * 获取最近的两条任务信息
	 * @return
	 */
	public List<Task> getTop2(){
		String sql="select task.*,tw."+TaskWh.CLICK_NUM+" num from "+TaskWh.dao.tableName()+" tw left join "+Task.dao.tableName()+" task on task."+Task.ID+"=tw."+TaskWh.TASK_ID+" where "+TaskWh.WH_ID+ "=? and tw."+TaskWh.DELETETAG+"="+TaskWh.DELETE_STATUS_NO+" GROUP BY "+TaskWh.TASK_ID+" ORDER by "+TaskWh.CREATE_TIME+" desc LIMIT 2";
		return Task.dao.findByCache(Fair.FAIR_CACHE_NAME,FAIR_CACHE_TOP_CREATETIME+get(ID),sql,new Object[]{get(ID)});
	}


	@Override
	public String tableName() {
		return "fair_wh";
	}

	
	public String age(){
		
		String result="未知";
		if(getStr(BIRTHDAY)!=null){
			Calendar cal = Calendar.getInstance();  
			  
	        if (cal.before(getStr(BIRTHDAY))) {return result;  
	        }  
	        int yearNow = cal.get(Calendar.YEAR);  
	        int monthNow = cal.get(Calendar.MONTH);  
	        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);  
	        cal.setTime(DateUtils.string2Date(getStr(BIRTHDAY), DateUtils.YYMMdd_FORMAT));  
	  
	        int yearBirth = cal.get(Calendar.YEAR);  
	        int monthBirth = cal.get(Calendar.MONTH)+1;  
	        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);  
	  
	        int age = yearNow - yearBirth;  
	  
	        if(monthBirth>=9 && monthBirth<=12){
	        	if(dayOfMonthBirth>=2 && dayOfMonthBirth<=31){
	        		 age--;  
	        	}
	        }else if (monthNow <= monthBirth) {  
	            if (monthNow == monthBirth) {  
	                if (dayOfMonthNow < dayOfMonthBirth) age--;  
	            }else{  
	                age--;  
	            }  
	        }
	        result = age+""; 
		}
		return result;
	}

	
	
	public String constellation(){
		
		String result = "未知";
		if(getStr(BIRTHDAY)!=null){
			Date date= DateUtils.string2Date(getStr(BIRTHDAY), DateUtils.YYMMdd_FORMAT);
			Calendar now = Calendar.getInstance();
			now.setTime(date);
			result = getAstro(now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH));
		}
		return result;
	}
	
	private static String getAstro(int month, int day) {
	    String[] starArr = {"水瓶座", "双鱼座", "白羊座",
	        "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座","魔羯座"};
	    int[] DayArr = {20,19,21,20,21,22,23,23,23,24,23,22};  // 两个星座分割日
		int index=month;
	    if(day<DayArr[month]){
	    	index = (index-1<0)?11:index-1;
	    }
	    return starArr[index];
		
		
	}
	
	public static void main(String[] args) {
		System.out.println(getAstro(0,19));//摩羯座
		System.out.println(getAstro(0,20));//水瓶座
		System.out.println(getAstro(11,20));//射手座
	}
	
	
}